# -*- coding: utf-8 -*-
# @Date：2024/7/20 19:39:46
# @Author：CJiaの青姝
# @FileName：login
# @Editor：PyCharm2024
# @Remark：
from typing import Any

from django.forms import model_to_dict
from typing_extensions import Self

from backend.settings import WHITE_USER_LIST
from auths.models import Users, UsersToken
from ninja import Router, Field, Schema, ModelSchema
from utils.cj_md5 import md5_encrypt
from utils.cj_jwt import generate_token
from utils.request_util import save_login_log
from utils.userinfo import get_user_info_from_token, get_user_logout_token
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class LoginSchemaIn(Schema):
    username: str = Field(..., description="用户名", alias="username")
    password: str = Field(..., description="密码", alias="password")

    def validate(cls, value: Any) -> Self:
        if value.username.strip() is None or value.password.strip() is None:
            return "用户名或密码不能为空", False
        else:
            value.password = md5_encrypt(value.password)
            return value, True

    class Config:
        title = "用户登录参数"


class LoginSchemaOut(Schema):
    token: str = Field(None, description="token", alias="token")
    bearerToken: str = Field(None, description="完整token", alias="bearerToken")

    class Config:
        title = "登录实例"


class UserSchemaOut(ModelSchema):
    is_superuser: bool = Field(False, description="是否超级用户", alias="is_superuser")
    roles: list = Field([], description="角色id列表", alias="roles")
    permissions: list = Field([], description="权限操作符列表", alias="permissions")

    class Config:
        title = '用户信息实例'
        model = Users
        model_exclude = ['password', 'password_str']


@router.post("/login", auth=None, response=LoginSchemaOut, summary="用户登录")
def login(request, data: LoginSchemaIn):
    message, verify = data.validate(data)
    if verify:
        # 校验用户名或者密码
        user_obj = Users.objects.filter(**data.dict()).first()
        if user_obj:
            request.user = user_obj
            user_obj_dic = model_to_dict(user_obj)
            if user_obj_dic['username'] in WHITE_USER_LIST:
                user_obj_dic['is_superuser'] = True
            else:
                user_obj_dic['is_superuser'] = False
            # 生成token
            jwt = generate_token(user_obj_dic, UsersToken)
            result = {
                "token": jwt,
                "bearerToken": f"Bearer {jwt}",
            }
            save_login_log(request=request)
            return SuccessResponse(data=result, msg="登录成功", code=200)
        else:
            return ErrorResponse(msg="账号或密码错误", code=400)
    else:
        return ErrorResponse(msg=message, code=400)


@router.post("/logout", auth=None, summary="用户退出登录")
def logout(request):
    # 调用用户注销方法
    result = get_user_logout_token(request)
    # 返回结果
    return SuccessResponse(msg=result, code=200)


@router.get("/userinfo", response=UserSchemaOut, summary="获取用户信息")
def userinfo(request):
    """ 用于前端获取当前用户的所有信息"""
    user_info = get_user_info_from_token(request)
    # 返回结果
    return user_info
